<template>
  <div id="mainL" style="width: 100%; height: 650px;"></div>
</template>

<script>
import * as echarts from 'echarts';
import axios from "axios";

export default {
  name: "companyStatisticsLeft",
  methods: {
    fetchJobs() {
      axios.get(`/api/jobs/find/${this.$store.state.companyId}`).then(resp => {
        const jobsData = resp.data;
        const categoryCount = {};
        jobsData.forEach(job => {
          const categoryId = job.categoryId;
          if (categoryCount[categoryId]) {
            categoryCount[categoryId]++;
          } else {
            categoryCount[categoryId] = 1;
          }
        });
        const resultArray = Object.keys(categoryCount).map(key => ({
          category_id: parseInt(key),
          count: categoryCount[key]
        }));

        const updatedResultArray = [];
        const promises = resultArray.map(item => {
          return axios.get(`/api/category/name/${item.category_id}`).then(categoryResp => {
            const categoryName = categoryResp.data;
            return {
              category_name: categoryName,
              count: item.count
            };
          });
        });

        Promise.all(promises).then(updatedData => {
          updatedResultArray.push(...updatedData);
          const chartDom = document.getElementById('mainL');
          const myChart = echarts.init(chartDom);
          const xAxisData = updatedResultArray.map(item => item.category_name);
          const seriesData = updatedResultArray.map(item => item.count);

          const option = {
            xAxis: {
              type: 'category',
              data: xAxisData
            },
            yAxis: {
              type: 'value'
            },
            series: [
              {
                data: seriesData,
                type: 'bar',
                showBackground: true,
                backgroundStyle: {
                  color: 'rgba(180, 180, 180, 0.2)'
                }
              }
            ]
          };

          myChart.setOption(option);
        }).catch(error => {
          console.error('获取分类名称数据出错：', error);
        });
      }).catch(error => {
        console.error('获取职位数据出错：', error);
      });
    }
  },
  mounted() {
    this.fetchJobs();
  }
}
</script>

<style scoped>
label {
  font-size: 16px;
  color: #333;
  margin-bottom: 10px;
}

#mainL {
  flex: 1;
}
</style>
